package com.sunmi.usercenter.ui.activity.fragment;

import java.lang.reflect.Type;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.Shop;
import com.sunmi.usercenter.bean.UserLoginInfo;
import com.sunmi.usercenter.bean.rpc.ReqLogin;
import com.sunmi.usercenter.bean.rpc.ReqReSetPassword;
import com.sunmi.usercenter.bean.rpc.ReqSetPassword;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import com.sunmi.usercenter.utils.MD5Utils;

import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 项目名称：Sunmi-User-Center
 * 类描述 设置密码的界面
 * 创建人：Abtswiath丶lxy
 * 创建时间：2016/6/7 11:38
 * 修改人：longx
 * 修改时间：2016/6/7 11:38
 * 修改备注：
 */
public class SettingPsdFragment extends SuperFragment implements OnClickListener,TextWatcher{

	private View mView;
	private RelativeLayout mRelBack,mRelClear;
	private EditText mEditPsd1;
	private LinearLayout mLinShowPsd;
	private TextView mTxtPsdError,mTxtSuccess;
	private ImageView mImgEye;  
	private boolean isHidden = true;//是否隐藏输入框文本
	private  boolean editUsernameIsNull = true;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
	}
	
	/**
	 * 初始化
	 */
	private void initView() {
		mActivity.SetStatusColorf5f5f5();
		mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
		mEditPsd1 = (EditText) mView.findViewById(R.id.txt_password1);
		mLinShowPsd = (LinearLayout) mView.findViewById(R.id.ln_show_psd);
		TextView mTxtTitle = (TextView) mView.findViewById(R.id.title);
		mRelClear = (RelativeLayout) mView.findViewById(R.id.rel_clear);
		layoutTitle(mTxtTitle);

		mTxtPsdError = (TextView)mView.findViewById(R.id.txt_error);
		mTxtSuccess = (TextView)mView.findViewById(R.id.btn_login);
		mImgEye = (ImageView)mView.findViewById(R.id.img_show_psd);
		mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.waitting));
		if(Constant.mInputToCode.getFramgment()==2){
			mTxtTitle.setText(getString(R.string.reset_password));
			mTxtSuccess.setText(getString(R.string.reset_success));
		}else{
			mTxtTitle.setText(getString(R.string.set_password));
			mTxtSuccess.setText(getString(R.string.success_register_and_login));
		}
		mTxtPsdError.setVisibility(View.GONE);
		mTxtSuccess.setOnClickListener(this);
		mRelBack.setOnClickListener(this);
		mLinShowPsd.setOnClickListener(this);
		mEditPsd1.addTextChangedListener(this);
		mRelClear.setOnClickListener(this);
		changeLoginBtn();
		mEditPsd1.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				editUsernameIsNull = s.length()<6;
				changeLoginBtn();
			}
		});
	}

	private void changeLoginBtn(){
		if(!editUsernameIsNull){
			mTxtSuccess.setBackgroundResource(R.drawable.btn_bg);
			mTxtSuccess.setEnabled(true);
		}else{
			mTxtSuccess.setBackgroundResource(R.drawable.btn_bg_no_click2);
			mTxtSuccess.setEnabled(false);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return mView = inflater.inflate(R.layout.fragment_settings_psd,container,false);
	}
	
	/**
	 * 是否显示文本框的内容
	 */
	private void showPsdOrHidePsd(){
		if(isHidden){
			mEditPsd1.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
			mImgEye.setBackgroundResource(R.drawable.eye_yes);
		}else{
			mEditPsd1.setTransformationMethod(PasswordTransformationMethod.getInstance());
			mImgEye.setBackgroundResource(R.drawable.eye_no);
		}
		isHidden = !isHidden;
		mEditPsd1.postInvalidate();
		//切换后将EditText光标置于末尾
        CharSequence charSequence = mEditPsd1.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
	}
	
	/**
	 * 点击完成注册，并登录
	 */
	private void clickToSuccess(){
		String psd1 = mEditPsd1.getText().toString();
		if(psd1.length()<6){
			mTxtPsdError.setVisibility(View.VISIBLE);
			return;
		}else{
			mTxtPsdError.setVisibility(View.GONE);
			if(Constant.mInputToCode.getFramgment()==1){
				setPsd(psd1);
			}else{
				resetPsd(psd1);
			}
		}
	}
	
	
	private LoadingDialog mLoadingDialog;
	private void resetPsd(final String password){
		mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.waitting));
		mLoadingDialog.show();
		ReqReSetPassword reqSetPassword = new ReqReSetPassword();
		reqSetPassword.setPassword(MD5Utils.md5Password(Constant.mInputToCode.getUsername(), password));
		reqSetPassword.setUserName(Constant.mInputToCode.getUsername());
		reqSetPassword.setCode(Constant.mInputToCode.getCode());
		mHttpController.reSetPassword(reqSetPassword, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				Analysis(password, arg2);
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				showToast(getString(R.string.req_error));
				mLoadingDialog.dismiss();
			}
		});
	}
	
	
	private void setPsd(final String password){
		mLoadingDialog.show();
		ReqSetPassword reqSetPassword = new ReqSetPassword();
		reqSetPassword.setPassword(MD5Utils.md5Password(Constant.mInputToCode.getUsername(), password));
		reqSetPassword.setUserName(Constant.mInputToCode.getUsername());
		reqSetPassword.setCode(Constant.mInputToCode.getCode());
		mHttpController.setPassword(reqSetPassword, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				Analysis(password, arg2);
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				showToast(getString(R.string.req_error));
				mLoadingDialog.dismiss();
			}
		});
	}

	private void login(final UserLoginInfo loginInfo){
		ReqLogin reqLogin = new ReqLogin();
		reqLogin.setPassword(MD5Utils.md5Password(loginInfo.getUsername(), loginInfo.getPassword()));
		reqLogin.setUserName(loginInfo.getUsername());
		mHttpController.login(reqLogin, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String json = new String(arg2);
				Gson gson = new Gson();
				Type type = new TypeToken<Result<Shop>>(){}.getType();
				Result<Shop> result = null;
				try {
					result = gson.fromJson(json,type);
				}catch (Exception e){
					e.printStackTrace();
				}
				if(result!=null&&result.getCode()==1){
					mCaCheModel.saveLoginUserName(loginInfo.getUsername());
					if(result.data!=null){
						mCaCheModel.saveShop(result.data);
					}
				}else{
					
				}
				mLoadingDialog.dismiss();
				if(Constant.ME_IS_LAUNCHER){
					exitMe();
//					getActivity().finish();
				}else {
					openFM(new FmInfo(LoginFragment.class, null));
				}
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				mLoadingDialog.dismiss();
				showToast(getString(R.string.login_eror));
				openFM(new FmInfo(LoginFragment.class, null));
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			onBack();
			break;
		case R.id.ln_show_psd:
			showPsdOrHidePsd();
			break;
		case R.id.btn_login:
			clickToSuccess();
			break;
			case R.id.rel_clear:
				mEditPsd1.setText("");
				break;
		default:
			break;
		}
	}

	/**
	 * @param password
	 * @param arg2
	 */
	private void Analysis(final String password, byte[] arg2) {
		String json = new String(arg2);
		Gson gson = new Gson();
		@SuppressWarnings("rawtypes")
		Result result = null;
		try {
			result = gson.fromJson(json, Result.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(result!=null&&result.code==1){
			UserLoginInfo userLoginInfo = new UserLoginInfo();
			userLoginInfo.setPassword(password);
			userLoginInfo.setUsername(Constant.mInputToCode.getUsername());
//			mCaCheModel.saveUserPasswordAndUsername(userLoginInfo);
//			if (Constant.ME_IS_LAUNCHER) {
//				if (Constant.mInputToCode.getFramgment() == 1) {
//					mLoadingDialog.dismiss();
//					exitMe();
//					getActivity().finish();
//				} else {
					login(userLoginInfo);
//				}
//				login(userLoginInfo);
//			}
		} else {
			mLoadingDialog.dismiss();
			showToast(getString(R.string.set_fail_to_try));
		}
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		if(s.length()>0){
			mRelClear.setVisibility(View.VISIBLE);
		}else{
			mRelClear.setVisibility(View.GONE);
		}
	}
}
